#include <list>
#include <ctime>
#include <iostream>
#include <iterator>
#include <deque>
#include "product.h"

using namespace std;
namespace a4
{
  struct stocked_item
  {
    int days_until_expired;
    int quantity;
  };

    
  
  product::product (string UPC, int days_till_expired)
  {
    this->upc = UPC;
    activity_count = 0;
    shelf_life = days_till_expired;
    item_stock = new std::deque<a4::stocked_item>();
		
	
  }
    
    void  product::addItem(int number_of_items)
  {
      stocked_item new_item;
      new_item.days_until_expired = shelf_life;
      new_item.quantity = number_of_items;
      item_stock->push_back(new_item);
      activity_count +=  number_of_items;
  }
  
	int product::getTotalNumberOfItems()
	{
		int result = 0;
		deque<a4::stocked_item>::iterator iter;
		for(iter = item_stock->begin();iter !=item_stock->end();iter++)
		{
			result += iter->quantity;
		}
		return result;
	}
	
  void product::removeItem(int quantity)
  {
      int ammount_sent = 0;
		int remaining = quantity;
      
      while(item_stock->size() > 0 && remaining > 0)
      {
				
          if(item_stock->front().quantity <= remaining)
          {
						ammount_sent = item_stock->front().quantity;
						remaining -= ammount_sent;
						activity_count += item_stock->front().quantity;
						item_stock->pop_front();
						
          }
          else
          {
				
						stocked_item temp;
						temp.quantity = item_stock->front().quantity - remaining;
						temp.days_until_expired = item_stock->front().days_until_expired;
						
						item_stock->pop_front();
						item_stock->push_front(temp);
		
						activity_count += remaining;
						ammount_sent += remaining;
						break;
          }
				
      }
		
  }
  
	int product::getActivityCount()
	{
		return activity_count;
	}
	
  void product::calculate_expirations_for_new_day()
  {
      
      for( std::deque<stocked_item>::iterator i(item_stock->begin()), end(item_stock->end()); i != end;
          ++i )
      {
          i->days_until_expired = i->days_until_expired -1;
          if(i->days_until_expired == 0)
          {
            item_stock->pop_front();
          }
      }
		activity_count = 0;
  }
}
